#!/usr/bin/python
# beauty_trips.py : Sends a sentence to the TRIPS page and gets its semantics analysis and parse.
# using BeautifulSoup HMTL parser.
# Author: Federico Cirett Galan
PGK = "ua_cs665_trips"

from urllib2 import urlopen
#from ClientForm import ParseResponse
from BeautifulSoup import BeautifulSoup
import getopt
import re
import types
import time
import sys
import string
# ROS 
import roslib; roslib.load_manifest('ua_cs665_trips')
import rospy
from std_msgs.msg import String
from ua_cs665_trips.srv import *
#
def main(argv):
    try:
       opts, args = getopt.getopt(argv,"s:h",["sentence=","help"])
    except getopt.GetoptError,err:
       print str(err)
       usage()
       sys.exit(2)
    for opt, arg in opts:
       if opt in  ("-s", "--sentence"):
          trip_process(arg)
       elif opt in ("-h", "--help"):
          usage()
          sys.exit(2)
       
def trip_process(sentence):
    query = sentence.replace(' ','+')
    trips_url = "http://www.cs.rochester.edu/research/cisd/projects/trips/parser/cgi/web-parser-xml.cgi?input="
    url = trips_url+query
    print url
    page = urlopen(url)
    soup = BeautifulSoup(page)
    words = soup.findAll('words')
    t_words = words[1].findAll('lisp')
    text_words = t_words[0].text
    tree = soup.findAll('tree')
    t_tree = tree[1].findAll('lisp')
    text_tree = t_tree[0].text
    terms = soup.findAll('terms')
    t_term = terms[1].findAll('lisp')
    text_term= t_term[0].text
    if text_term != 'NIL':
      print "WORDS"
      print text_words
      print "TREE"
      print text_tree
      print "RDF"
      print text_term
    else:
      print "The sentence '%s' failed to parse\n" % sentence

def usage():
    print "beauty_trips.py -s:'a sentence example' -h"
    print "beauty_trips.py --sentence='a sentence example' --help"

if __name__ == "__main__":
    main(sys.argv[1:])
